package jwt

import (
	"gindemo/config"
	"gindemo/pkg/logger"
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// 1.获取jwt的secert
var jwtKey = []byte(config.JwtKey)

// 2.定义声明类型
type MyCustomClaims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// 3.生成token
func GenToken(username string) (string, error) {
	claims := MyCustomClaims{
		username,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * time.Duration(config.JwtExpTime))),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "tanlay",
			Subject:   "tanlay",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(jwtKey)
	return ss, err
}

// 4.解析token
func ParseJwt(ss string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(ss, &MyCustomClaims{},
		func(token *jwt.Token) (interface{}, error) {
			return jwtKey, nil
		})
	if err != nil {
		logger.Error(nil, "token解析失败")
		return nil, err
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		logger.Error(nil, "token不合法")
		return nil, errors.New("token不合法，invalid token")
	}
}
